/*
 * Copyright (c) 2011-2012 Alexander Dubu
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * o  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * o  Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 *
 * o  Neither the name Axil nor the names of its contributors may be used to
 *    endorse or promote products derived from this software without specific
 *    prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package axil.framework.localization;

import axil.api.*;
import axil.etc.NameValue;
import axil.framework.format.SimpleFormatting;

import static axil.framework.Functions.*;


/**
 * An object representing a translatable text message, but one that does not
 * force resolution and formatting of the value until it is actually required.
 * This can save a fair amount of memory and CPU churn when you are doing
 * something like validation, but are only interested in a yes/no answer, not
 * the formatted details.
 */
public class Message implements Formatted, Context {
	private final Namespace ns;
	private final String key;
	private final NameValue[] values;


	public Message(Namespace ns, String key, NameValue... values) {
		this.ns = ns;
		this.key = key;
		this.values = values;
	}


	public String key()	{
		return key;
	}


	/**
	 * Get the optional message values. Values are name/value pairs containing a
	 * key and the raw, unformatted value.
	 *
	 * @return
	 * 	Returns the message values. The array is never null, but may be empty.
	 */
	public Argument[] values() {
		return values;
	}


	/**
	 * Extract the current value for the given identifier from this context.
	 * This method is used only to extract root objects, not complex identifiers.
	 * For example, in the complex identifier `Shopping Cart.Items`, the get()
	 * method is used only to extract 'shopping-cart', not the entire value.
	 * This method is invoked by Accessor objects only.
	 *
	 * @param name
	 * 	The name of the identifier, either from a simple identifier or the root
	 * 	element from a compound identifier.
	 *
	 * @return
	 * 	Returns an appropriate object value. The null value may be safely
	 * 	returned. If this context does not contain the value, then it must
	 * 	delegate to the parent context. If the object is simply not in the
	 * 	context, then null is returned.
	 */
	public Object get(String name) {
		for (NameValue nv : values) {
			if (nv.key().equals(name)) {
				return nv.value();
			}
		}
		return null;
	}


	/**
	 * Extract the current value for the given identifier from this context.
	 *
	 * @param name
	 *	The name of the identifier, either from a simple identifier or the root
	 * 	element from a compound identifier.
	 *
	 * @return
	 * 	Returns the Axil object matching the given key. If this context does
	 * 	not contain the value, then it must delegate to the parent context. If
	 * 	the object is simply not in the context, then null is returned.
	 */
	public AxilObject at(String name) {
		Object v = get(name);
		return v == null ? null : axil(v);
	}


	/**
	 * Return the parent context on top of which this one relies. The contexts
	 * form a chain of immutable objects, allowing for the same contexts to be
	 * used safely across threads and also allow common identifiers to be defined
	 * only once.
	 *
	 * @return
	 * 	Returns the parent context. For a custom context implementation by the
	 * 	host application, the object returned can never be null.
	 */
	public Context parent() {
		return null;
	}


	/**
	 * Get the value of the given identifier. The value returned may be null
	 * if no such value is know to this object.
	 */
	public Object valueof(String ident) {
		for (NameValue nv : values) {
			if (nv.key().equals(ident)) {
				return nv.value();
			}
		}
		return null;
	}


	/**
	 * Print the raw contents of this including the message key and all of the
	 * raw values. This is useful when diagnosing problems with the translation
	 * system itself.
	 */
	public String dump() {
		StringBuilder b = new StringBuilder("key: ");
		b.append(key);
		for (NameValue v : values) {
			b.append('\n');
			b.append(v.key());
			b.append(" = ");
			b.append(str(v.value()));
		}
		return b.toString();
	}


	/**
	 * Format this object in a locale-friendly manner. The string returned is
	 * a localized representation of this object using the locale and timezone
	 * associated with this persona. The formatting given is never null and
	 * matches formatting suitable for this type.
	 */
	public String format(Persona persona, Formatting formatting) {
		return ns.translation(key, loc(persona)).format(persona,
		        this);
	}


	/**
	 * Return a string representation of this object. The string returned is
	 * never null.
	 */
	public String toString() {
		return format(persona(), SimpleFormatting.object);
	}
}
